home *** CD-ROM | disk | FTP | other *** search
- ; Quick sort. From Horowitz & Sahni pg 347
- ; Sort list[m..n] into assending order
-
- ; swap is a routine that interchanges list[a] with list[b]
- ; cmp compares list[a] with list[b] and returns:
- ; negative if list[a] < list[b]
- ; positive if list[a] > list[b]
- ; zero if list[a] = list[b]
-
- ; Modeled (a bit) after the lib C qsort()
- (defun
- Qsort (list-to-sort)(int m n)(pointer defun swap cmp)
- {
- (int i j)
-
- (if (>= m n) (done)) ;; end the recursion
- (i m) (j (+ n 1))
- (while TRUE
- {
- (while { (+= i 1)(and (<= i n) (< (cmp list-to-sort i m) 0)) } ())
- (while { (-= j 1)(> (cmp list-to-sort j m) 0) } ())
- (if (< i j) (swap list-to-sort i j) (break))
- })
- (swap list-to-sort m j)
- (Qsort list-to-sort m (- j 1) swap cmp)
- (Qsort list-to-sort (+ j 1) n swap cmp)
- }
- )
- ; swap and cmp routines for arrays of ints
- (defun
- swap (array int list-to-sort 1)(int a b) ; swap 2 elements
- {
- (int tmp)
- (tmp (list-to-sort a)) (list-to-sort a (list-to-sort b))
- (list-to-sort b tmp)
- }
- cmp (array int list-to-sort 1)(int a b) ; compare 2 elements
- { (- (list-to-sort a) (list-to-sort b)) }
- )
-
-
- (defun ;; Quick sort an array of ints
- QSort(array int vector 1)(int m n)
- {
- (int i j t k)
-
- (msg "==> " m " " n)
- (if (>= m n)(done))
- (i m)(j (+ n 1))(k (vector m))
- (while TRUE
- {
- (while { (+= i 1)(< (vector i) k)} ())
- (while { (-= j 1)(> (vector j) k)} ())
- (if (< i j)
- {
- (t (vector i))(vector i (vector j))(vector j t)
- }
- (break))
- })
- (t (vector m))(vector m (vector j))(vector j t)
- (QSort vector m (- j 1))
- (QSort vector (+ j 1) n)
- }
- )
-
- ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
- ;;;;;;;;;;;;;;;;; test ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
- ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
-
- (const NUMBER 0x03)
-
- (include random.mut)
-
- (array int list-to-sort 501) (int n j)
-
- (defun MAIN
- {
- (n (convert-to NUMBER (ask "n = ")))
-
- ;(srand 123)
- (for (j 0) (< j n)(+= j 1) (list-to-sort j (rand)))
-
- (for (j 0)(< j n)(+= j 1) (msg "Random list[" j "] = " (list-to-sort j)))
-
- ; (QSort list-to-sort 0 (- n 1))
- (Qsort list-to-sort 0 (- n 1) (floc swap) (floc cmp))
-
- (msg "--------------------------")
- (for (j 0)(< j n)(+= j 1) (msg "Sorted list[" j "] = " (list-to-sort j)))
- })
-